#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新闻管理控制器（合并版本）
将路由和控制器合并到一个类中
"""

from flask import Blueprint, jsonify, request, current_app
from services.app_service import AppService
from settings import get_logger

# API版本
API_VERSION = 'v1'

# 创建蓝图
news_bp = Blueprint('news', __name__, url_prefix='/api/news')

class NewsController:
    """
    新闻管理控制器
    负责新闻推送群组和时间设置的路由处理
    """
    
    def __init__(self):
        """
        初始化控制器并注册路由
        """
        self.app_service = AppService()
        self.logger = get_logger(__name__)
        self._register_routes()
    
    def _register_routes(self):
        """
        注册路由
        """
        news_bp.route('/groups', methods=['GET'])(self.get_news_groups)
        news_bp.route('/groups', methods=['POST'])(self.add_news_group)
        news_bp.route('/groups', methods=['DELETE'])(self.remove_news_group)
        news_bp.route('/time', methods=['POST'])(self.set_news_time)
        news_bp.route('/test', methods=['GET'])(self.test_news)
    
    def get_news_groups(self):
        """
        获取新闻推送群组列表
        
        Returns:
            JSON: 群组列表
        """
        self.logger.info("获取新闻推送群组列表")
        try:
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            config = app_instance.get_config()
            news_groups = config.get('news', {}).get('target_groups', [])
            
            return jsonify({
                "success": True,
                "data": news_groups,
                "count": len(news_groups)
            })
            
        except Exception as e:
            current_app.logger.error(f"获取新闻群组失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500
    
    def add_news_group(self):
        """
        添加新闻推送群组
        
        Returns:
            JSON: 添加结果
        """
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    "success": False,
                    "error": "请求数据为空"
                }), 400
            
            self.logger.info(f"添加新闻推送群组: {data}")
            
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            group_name = data.get('group_name')
            if not group_name:
                return jsonify({
                    "success": False,
                    "error": "缺少群组名称"
                }), 400
            
            success = app_instance.add_news_group(group_name)
            
            if success:
                return jsonify({
                    "success": True,
                    "message": f"已添加群组 '{group_name}' 到新闻推送列表"
                })
            else:
                return jsonify({
                    "success": False,
                    "error": "添加新闻推送群组失败"
                }), 500
                
        except Exception as e:
            current_app.logger.error(f"添加新闻群组失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500
    
    def remove_news_group(self):
        """
        移除新闻推送群组
        
        Returns:
            JSON: 移除结果
        """
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    "success": False,
                    "error": "请求数据为空"
                }), 400
            
            self.logger.info(f"移除新闻推送群组: {data}")
            
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            group_name = data.get('group_name')
            if not group_name:
                return jsonify({
                    "success": False,
                    "error": "缺少群组名称"
                }), 400
            
            success = app_instance.remove_news_group(group_name)
            
            if success:
                return jsonify({
                    "success": True,
                    "message": f"已从新闻推送列表中移除群组 '{group_name}'"
                })
            else:
                return jsonify({
                    "success": False,
                    "error": "移除新闻推送群组失败"
                }), 500
                
        except Exception as e:
            current_app.logger.error(f"移除新闻群组失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500
    
    def set_news_time(self):
        """
        设置新闻推送时间
        
        Returns:
            JSON: 设置结果
        """
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    "success": False,
                    "error": "请求数据为空"
                }), 400
            
            self.logger.info(f"设置新闻推送时间: {data}")
            
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            time = data.get('time')
            if not time:
                return jsonify({
                    "success": False,
                    "error": "缺少时间参数"
                }), 400
            
            success = app_instance.set_news_time(time)
            
            if success:
                return jsonify({
                    "success": True,
                    "message": f"已设置新闻推送时间为 {time}"
                })
            else:
                return jsonify({
                    "success": False,
                    "error": "设置新闻推送时间失败"
                }), 500
                
        except Exception as e:
            current_app.logger.error(f"设置新闻推送时间失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500
    
    def test_news(self):
        """
        测试新闻获取
        
        Returns:
            JSON: 测试结果
        """
        try:
            self.logger.info("测试新闻获取")
            
            app_instance = self.app_service.get_app_instance()
            
            if not app_instance:
                return jsonify({
                    "success": False,
                    "error": "微信后端应用未初始化"
                }), 500
            
            news_data = app_instance.test_news()
            
            return jsonify({
                "success": True,
                "data": news_data
            })
                
        except Exception as e:
            current_app.logger.error(f"测试新闻获取失败: {e}")
            return jsonify({
                "success": False,
                "error": str(e)
            }), 500

# 实例化控制器，确保路由被注册
news_controller = NewsController()